﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting.Messaging;

namespace Com.CloudTalk.Controller
{
    public class EventsService
    {
        private const int MaxEventWaitTime = 30000;     // request for events lasts at most 30 seconds

        public event EventsHandler GetMessagesCompleted;
        public delegate object[] GetEventsDelegate(string _sClientEmail);
        public delegate void EventsHandler(object sender, MessageArgs args);

        public void GetEventsAsync(string _sClientEmail)
        {
            GetEventsDelegate del = new GetEventsDelegate(Execute);
            
            del.BeginInvoke(
                _sClientEmail, 
                new AsyncCallback(Callback), 
                null);
        }

        private object[] Execute(string _sClientEmail)
        {
            /*CTClient c = CloudTalkController.GetClientByEmail(_sClientEmail);

            if (c == null)
            {
                return new object[] {
                    new
                    {
                        Code = 2,
                        Message = "O cliente especificado não faz parte desta sala de chat."
                    }
                };
            }
            
            if (CloudTalkController.WaitForEvent(c.Email, MaxEventWaitTime))
            {
                // the thread has been signaled
                var messages = CloudTalkController.Receive(c);
                var lstJson = new List<object>();

                foreach (CTEvent m in messages)
                {
                    lstJson.Add(new
                    {
                        EventObject = m.Text,
                        Sender = m.Sender.Name,
                        Timestamp = m.Timestamp.ToShortTimeString(),
                        EventType = m.Type.ToString()
                    });
                }

                return lstJson.ToArray();
            }

            // no signal received
            return new object[] { };*/
            System.Threading.Thread.Sleep(MaxEventWaitTime);
            return new object[] { };
        }

        private void Callback(IAsyncResult ar)
        {
            AsyncResult result = (AsyncResult)ar;
            GetEventsDelegate del = (GetEventsDelegate)result.AsyncDelegate;

            object[] retVal = del.EndInvoke(result);

            if (this.GetMessagesCompleted != null)
            {
                this.GetMessagesCompleted(this, new MessageArgs() 
                { 
                    Sender = this,
                    Messages = retVal
                });
            }
        }
    }

    public class MessageArgs : EventArgs
    {
        public object Sender { get; set; }
        public object[] Messages { get; set; }

        public MessageArgs()
        {
        }
    }
}
